import re

from app.api.system.schemas import permission_schema
from app.db.session import SessionLocal
from app.models.system import Permission
from app.utils.curd_base import ModelCRUD
from sqlalchemy.orm import Session
from fastapi.routing import APIRoute


class CRUDPermission(ModelCRUD):
    model = Permission

    def url_get_object(self, db: Session, url: str):

        instance = db.query(self.model).filter(self.model.url == url, self.model.is_delete == 0).first()
        return instance


crud_permission = CRUDPermission()


def replace_url_update_id(url):
    pattern = r"{.+}"
    return re.sub(pattern, "{id}", url)


def auto_create_router_permission(app):
    exclude_li = ['/assets', '/docs/oauth2-redirect', '/v1/docs', '/v1/openapi.json', '/v1/redoc']
    db = SessionLocal()
    for route in app.routes:
        if route.path not in exclude_li and isinstance(route, APIRoute):
            print(route)
            # print(route.path, route.name, route.tags, route.methods, route)
            group = route.tags[0] if getattr(route, "tags", None) else None
            url = replace_url_update_id(route.path)
            instance = crud_permission.url_get_object(db, url=url)
            if instance:
                pass
                # dit = {
                #     'name': route.name,
                #     "url": url,
                #     "group": group,
                #     "method": tuple(route.methods)[0]
                # }
                # data = permission_schema.CreatePermission(**dit)
                # crud_permission.update(db, instance=instance,data=data)
            else:
                method = tuple(route.methods)[0] if getattr(route, "methods", None) else "GET"
                dit = {
                    'name': route.name if route.name else "权限接口",
                    "url": url,
                    "group": group,
                    "method": method
                }
                data = permission_schema.CreatePermission(**dit)
                crud_permission.create(db, data=data)
